package com.luis.toolbox.inbound;

import com.luis.toolbox.common.EquipMappingConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/")
public class Router implements ApplicationContextAware {

	private final Logger log = LoggerFactory.getLogger(Router.class);

	@Autowired
	private EquipMappingConfig config;
	private final CommitState commitState;
	private ApplicationContext context;

	public Router(CommitState commitState) {
		this.commitState = commitState;
	}

	/*
	 * body 格式：
	 * history,company_id=15,item_code=GWM_C_TA1_TL1_TW001_TE02_AB001 value=0.0 1627374291073000000
	 * history,company_id=15,item_code=A_TA1_TL1_TW001_TE02_AL001 value=12 1627374291073000000
	 * */
	@PostMapping("/write")
	public Mono<String> receive(@RequestBody String data){
		try{
			synchronized (commitState){
				commitState.addMessage(data);
			}
		}catch(Exception ex){
			log.error("error when add message to store, ", ex);
		}
		return Mono.empty();
	}

	@GetMapping("/test")
	public Mono<String> test(@RequestParam("equip") String k){
		String result = config.get(k);
		if(StringUtils.isBlank(result)) return Mono.just("not configured for "+k);
		return Mono.just(result);
	}

	@GetMapping("/status")
	public Mono<String> status(){
		String status = commitState.toString();
		return Mono.just(status);
	}

	@GetMapping("/shutdown")
	public Mono<String> shutdown(){
		ConfigurableApplicationContext ctx = (ConfigurableApplicationContext)context;
		ctx.close();
		return Mono.just("shutdown...");
	}

	@PostMapping("/testHttpMethod")
	public Mono<String> testHttpMethod(@RequestBody String data){
		System.out.println(data);
		return Mono.just("success");
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}
}
